package com.troyhigh.njrotc.admintracker;

import java.util.ArrayList;
import java.io.*;

/**
 * Java gave me the gift of serialization, so I decided to build a database
 * around it. This may effectively eliminate the TXTDatabase.
 * 
 * @author Quan Nguyen
 * @version 2008-December-25
 */
public class SERDatabase implements Database
{
    private ArrayList<Cadet> cadets;
    private ArrayList<Event> events;
    
    private boolean autocommit = false;
            
    private final String CADETS = "cadets";
    private final String EVENTS = "events";
    
    private final String EXTENSION = ".ats";
    private final String SEPARATOR = File.separator;
    private final String DIRECTORY = "library";
    
    private final String BACKUPDIR = "backup";
    
    public void connect() 
    {
        loadCadets(DIRECTORY + SEPARATOR + CADETS + EXTENSION);
        loadEvents(DIRECTORY + SEPARATOR + EVENTS + EXTENSION);
    }

    @SuppressWarnings("unchecked")
    private void loadCadets(String filename)
    {
        try
        {
            ObjectInputStream stream = new ObjectInputStream(new FileInputStream(filename));
            cadets = ((ArrayList<Cadet>)stream.readObject());
            stream.close();
        }
        catch (InvalidClassException e)
        {
            System.out.println("[serial error] This file is for an old version of AdminTracker.");
        }
        catch (Exception e)
        {
            System.out.println("[serial error] Cadets file failed to be read.");
            //e.printStackTrace();
        }
    }
    
    @SuppressWarnings("unchecked")
    private void loadEvents(String filename)
    {
        try
        {
            ObjectInputStream stream = new ObjectInputStream(new FileInputStream(filename));
            events = ((ArrayList<Event>)stream.readObject());
            stream.close();
        }
        catch (InvalidClassException e)
        {
            System.out.println("[serial error] This file is for an old version of AdminTracker.");
        }
        catch (Exception e)
        {
            System.out.println("[serial error] Events file failed to be read.");
            //e.printStackTrace();
        }
    }
    
    public boolean isConnected() 
    {
        return true;
    }

    public void commit() 
    {
        saveCadets(DIRECTORY + SEPARATOR + CADETS + EXTENSION);
        saveEvents(DIRECTORY + SEPARATOR + EVENTS + EXTENSION);
    }
    
    @SuppressWarnings("unchecked")
    private void saveCadets(String filename)
    {
        try
        {
            ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(filename));
            stream.writeObject(cadets);
            stream.close();
        }
        catch (Exception e)
        {
            System.out.println("[serial error] Cadets file failed to be saved.");
        }
    }
    
    @SuppressWarnings("unchecked")
    private void saveEvents(String filename)
    {
        try
        {
            ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(filename));
            stream.writeObject(events);
            stream.close();
        }
        catch (Exception e)
        {
            System.out.println("[serial error] Events file failed to be saved.");
        }
    }

    public void disconnect() 
    {
        System.out.println("[note] SERDatabase does not require disconnection.");
    }

    public boolean isAutoCommit() 
    {
        return autocommit;
    }

    public void setAutoCommit(boolean auto) 
    {
        autocommit = auto;
    }

    public boolean canBackup() 
    {
        return true;
    }

    public void backup() 
    {
        String longTime = "" + (new java.util.Date()).getTime();
        File direct = new File(DIRECTORY + SEPARATOR + BACKUPDIR + SEPARATOR + longTime);
        direct.mkdir();
        saveCadets(DIRECTORY + SEPARATOR + BACKUPDIR + SEPARATOR + longTime + SEPARATOR + CADETS + EXTENSION);
        saveEvents(DIRECTORY + SEPARATOR + BACKUPDIR + SEPARATOR + longTime + SEPARATOR + EVENTS + EXTENSION);
        System.out.println("[serial backup] Backup complete.");
    }
    
    public void restore(String filename)
    {
        try
        {
            String line = filename;
            if(line.matches("\\d*\\d"))
            {
                File directory = new File(DIRECTORY + SEPARATOR + BACKUPDIR + SEPARATOR + line);
                File cadetsFile = new File(directory, "cadets" + EXTENSION);
                File eventsFile = new File(directory, "events" + EXTENSION);
                if(cadetsFile.exists() && eventsFile.exists())
                {
                    loadCadets(DIRECTORY + SEPARATOR + BACKUPDIR + SEPARATOR + line + SEPARATOR + CADETS + EXTENSION);
                    loadEvents(DIRECTORY + SEPARATOR + BACKUPDIR + SEPARATOR + line + SEPARATOR + EVENTS + EXTENSION);
                    System.out.println("[restore] AdminTracker files restored.");
                }
                else
                {
                    System.out.println("[error] The backup directory is invalid.");
                }
            }
            else
            {
                System.out.println("[error] Not a valid backup directory.");
            }
            
        }
        catch(Exception e)
        {
            System.out.println("[error] Error in restoring from backup.");
        }
    }

    public ArrayList<Cadet> getCadets() 
    {
        return cadets;
    }

    public ArrayList<Event> getEvents() 
    {
        return events;
    }

    public void setCadets(ArrayList<Cadet> array) 
    {
        cadets = array;
    }

    public void setEvents(ArrayList<Event> array) 
    {
        events = array;
    }
}